package com.hmkj.web.controller.trade;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.page.BasePageParams;
import com.hmkj.common.page.Pages;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.eolinker.endpoints.QuotationEndpoint;
import com.hmkj.core.eolinker.models.ModelRealTime;
import com.hmkj.core.eolinker.models.StockListModel;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.myChoose.MyChooseMapper;
import com.hmkj.core.model.myChoose.MyChooseModel;
import com.hmkj.core.po.myChoose.MyChoose;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.myChoose.MyChooseService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ......................我佛慈悲......................
 * ......................_oo0oo_.......................
 * .....................o8888888o......................
 * .....................88" . "88......................
 * .....................(| -_- |)......................
 * .....................0\  =  /0......................
 * ...................___/`---'\___....................
 * ..................' \\|     |// '...................
 * ................/ \\|||  :  |||// \.................
 * .............../ _||||| -卍-|||||- \................
 * ..............|   | \\\  -  /// |   |...............
 * ..............| \_|  ''\---/''  |_/ |...............
 * ..............\  .-\__  '-'  ___/-. /...............
 * ............___'. .'  /--.--\  `. .'___.............
 * .........."" '<  `.___\_<|>_/___.' >' ""............
 * ........| | :  `- \`.;`\ _ /`;.`/ - ` : | |.........
 * ........\  \ `_.   \_ __\ /__ _/   .-` /  /.........
 * ....=====`-.____`.___ \_____/___.-`___.-'=====......
 * ......................`=---='.......................
 * ....................................................
 * .................佛祖开光 ,永无BUG...................
 */
@Api(description = "自选")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/trade/choose")
public class AppMyChooseController extends GenericController<Integer, Order> {

    @Resource
    private MyChooseService myChooseService;

    @ApiOperation(value = "我的自选列表", notes = "我的自选列表")
    @RequestMapping(value = "/myChooseList", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity myChooseList(@ModelAttribute BasePageParams basePageParams) throws Exception {
        User user = getLoginUser();
        //持仓中，待平仓 平仓中 待结算 的订单
        Map<String, Object> param = new HashMap<>();
        param.put("userId", user.getId());
        param.put("basePageParams", basePageParams);
        Pages<MyChooseModel> pages = myChooseService.selectByPage(basePageParams,
                q -> ((MyChooseMapper) q).findCountForChoose(param),
                q -> ((MyChooseMapper) q).findListForChoose(param));
        List<MyChooseModel> myChooseList = pages.getRows();
        if (CollectionUtils.isNotEmpty(myChooseList)) {
            for (MyChooseModel myChoose : myChooseList) {
                ModelRealTime realTime = QuotationEndpoint.realtime(myChoose.getCode());
                if (realTime != null) {
                    myChoose.setLastPrice(realTime.getLast_price());
                    myChoose.setRisePre(realTime.getRise_pre());
                    myChoose.setStatus(realTime.getStatus());
                }
            }
        }
        pages.setRows(myChooseList);
        return ok(m -> {
            m.put("data", pages);
        });
    }

    @ApiOperation(value = "添加自选", notes = "添加自选")
    @RequestMapping(value = "/addMyChoose", method = RequestMethod.POST)
    public ResultEntity addMyChoose(@ApiParam("股票代码") @RequestParam(required = true) String code) throws Exception {
        User user = getLoginUser();
        if (StringUtils.isBlank(code)) {
            throw new BussinessException("请选择股票");
        }
        List<StockListModel> upList = redisService.getList(CacheID.STOCK_LIST_PREFIX, StockListModel.class);
        if (upList == null) {
            throw new BussinessException("参数错误");
        }
        //查询是否已添加过自选
        MyChoose choose = myChooseService.selectOne(new MyChoose(t -> {
            t.setUserId(user.getId());
            t.setCode(code);
        }));
        if (null != choose) {
            throw new BussinessException("请勿重复添加！");
        }
        Integer sortNum;
        List<MyChoose> list = myChooseService.select(new MyChoose(t -> {
            t.setUserId(user.getId());
        }));
        if (CollectionUtils.isNotEmpty(list)) {
            sortNum = list.size() + 1;
        } else {
            sortNum = 1;
        }
        MyChoose myChoose = new MyChoose();
        for (StockListModel up : upList) {
            if (up.getStock_code().equalsIgnoreCase(code)) {
                myChoose.setName(up.getCode_name());
            }
        }
        myChooseService.insert(new MyChoose(t -> {
            t.setName(myChoose.getName());
            t.setCode(code);
            t.setUserId(user.getId());
            t.setIsTop(MyChoose.ISTOP.T1.code);
            t.setSort(sortNum);
        }));
        return ok("添加自选成功",ResultEntity.SUCCESS);
    }


    @ApiOperation(value = "设置置顶", notes = "设置置顶")
    @RequestMapping(value = "/setTop", method = RequestMethod.POST)
    public ResultEntity setTop(@ApiParam("自选Id") @RequestParam(required = true) Integer id) throws Exception {
        User user = getLoginUser();
        //将用户自选的已置顶的都取消
        List<MyChoose> list = myChooseService.select(new MyChoose(T->{
            T.setUserId(user.getId());
            T.setIsTop(2);
        }));
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(t -> {
                myChooseService.updateByPrimaryKeySelective(new MyChoose(m -> {
                    m.setId(t.getId());
                    m.setIsTop(MyChoose.ISTOP.T1.code);
                }));
            });
        }
        MyChoose memberMyChoose = myChooseService.selectByPrimaryKey(id);
        if (null != memberMyChoose) {
            myChooseService.updateByPrimaryKeySelective(new MyChoose(t -> {
                t.setId(memberMyChoose.getId());
                t.setIsTop(MyChoose.ISTOP.T2.code);
            }));
        }
        return ok("设置置顶成功",ResultEntity.SUCCESS);
    }

    @ApiOperation(value = "删除自选--code", notes = "删除自选--code")
    @RequestMapping(value = "/delChooseByCode", method = RequestMethod.POST)
    public ResultEntity delChooseByCode(@ApiParam("股票代码") @RequestParam(required = true) String code,
                                        @ModelAttribute BasePageParams basePageParams) throws Exception {
        User user = getLoginUser();
        if (StringUtils.isBlank(code)) {
            throw new BussinessException("股票代码参数错误");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("userId", user.getId());
        param.put("code", code);
        param.put("basePageParams", basePageParams);
        MyChoose myChoose = myChooseService.selectOne(new MyChoose(t -> {
            t.setUserId(user.getId());
            t.setCode(code);
        }));
        if (null == myChoose) {
            throw new BussinessException("自选数据为空");
        }
        myChooseService.deleteByPrimaryKey(myChoose.getId());
        return ok("删除自选成功",ResultEntity.SUCCESS);
    }

    @ApiOperation(value = "删除自选--Ids", notes = "删除自选--Ids")
    @RequestMapping(value = "/delChooses", method = RequestMethod.POST)
    public ResultEntity delChooses(@ApiParam("Ids") @RequestParam(required = true) String ids) throws Exception {
        if (StringUtils.isNotBlank(ids)) {
            String[] split = ids.split(",");
            for (int i = 0; i < split.length; i++) {
                Integer id = Integer.parseInt(split[i]);
                MyChoose myChoose = myChooseService.selectByPrimaryKey(id);
                if (null != myChoose) {
                    myChooseService.deleteByPrimaryKey(id);
                }
            }
        }
        return ok("删除自选成功");
    }

    @ApiOperation(value = "我的自选-拖动", notes = "我的自选-拖动")
    @RequestMapping(value = "/dragMychoose", method = RequestMethod.POST)
    public ResultEntity dragMychoose(@ApiParam("Ids") @RequestParam(required = true) String ids) throws Exception {
        User user = getLoginUser();
        if (StringUtils.isNotBlank(ids)) {
            String[] split = ids.split(",");
            int length = split.length;
            for (int i = 0; i < length; i++) {
                Integer id = Integer.parseInt(split[i]);
                MyChoose myChoose = myChooseService.selectByPrimaryKey(id);
                int fi = i;
                if (null != myChoose) {
                    myChooseService.updateByPrimaryKeySelective(new MyChoose(t -> {
                        t.setId(myChoose.getId());
                        t.setSort(length - fi);
                    }));
                }
                if (i == 0) {
                    //将第一条数据设为置顶
                    List<MyChoose> list = myChooseService.select(new MyChoose(t -> {
                        t.setUserId(user.getId());
                    }));
                    if (CollectionUtils.isNotEmpty(list)) {
                        list.forEach(n -> {
                            myChooseService.updateByPrimaryKeySelective(new MyChoose(t -> {
                                t.setId(n.getId());
                                t.setIsTop(MyChoose.ISTOP.T1.code);
                            }));
                        });
                    }
                    myChooseService.updateByPrimaryKeySelective(new MyChoose(t -> {
                        t.setId(myChoose.getId());
                        t.setIsTop(MyChoose.ISTOP.T2.code);
                    }));
                }
            }
        }
        return ok("我的自选拖动成功");
    }
}